<template>
	<div class="sw_section_container" v-loading="loading">
		<div class="sw_query_form" v-if="$isHasAuth(topFrames)">
			<template v-if="userRole === 'member'">
				<div class="button" v-if="$isHasAuth(topButton)">
					<el-button type="primary" icon="el-icon-plus" v-hasPermi="'60c75eefa71e4162bcb961ac142fa4c3'" @click="handleOpenForm()">
						申请新实验
					</el-button>
					<template v-if="checkedData.length > 0">
						<el-button type="danger" icon="el-icon-delete" v-hasPermi="'4bf9b6b3eb9f47df9cd4e04417bf1583'" @click="handleBacthDelete()">
							删除
						</el-button>
					</template>
				</div>
			</template>
			<el-form size="small" inline v-hasPermi="queryBtn">
				<el-form-item>
					<el-input v-model="queryData.name" clearable placeholder="实验名称" style="width: 180px"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" icon="el-icon-search" @click="queryTableData">查询</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="sw_table_container">
			<template v-if="dataCount > 0">
				<el-table v-bind="tableConfig" :data="tableData" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
					<el-table-column type="selection" width="48" align="center" :selectable="selectableChecked"></el-table-column>
					<el-table-column label="状态" width="80" align="center" :formatter="statusFormatter"></el-table-column>
					<el-table-column label="批准时间" width="110" prop="auditTime" sortable :formatter="timeFormatter"></el-table-column>
					<el-table-column label="用户单位" width="240" prop="companyName" sortable></el-table-column>
					<el-table-column label="申请人" width="92" prop="createName" sortable></el-table-column>
					<el-table-column label="PI" width="92" :formatter="piNameFormatter"></el-table-column>
					<el-table-column label="实验名称" min-width="180" prop="name" sortable></el-table-column>
					<el-table-column label="测量技术" width="120" prop="filed1" sortable></el-table-column>
					<el-table-column label="机时" width="70" :formatter="applyHourFormmatter"></el-table-column>
					<el-table-column label="操作" fixed="right" :width="$controlWidth(tableButton)" v-if="$isHasAuth(tableButton)">
						<template slot-scope="{ row }">
							<el-button type="text" v-hasPermi="'25bd663cfb6844758245a5d4e690198c'" @click="handleLookData(row.id)">详情</el-button>
							<template v-if="userRole === 'member'">
								<template v-if="row.isSave === '2' || row.audit === '2'">
									<el-button type="text" v-hasPermi="'d5f4538b53704c49bb6d28cee6a68603'" @click="handleOpenForm(row.id)">编辑</el-button>
									<el-button type="text" v-hasPermi="'4bf9b6b3eb9f47df9cd4e04417bf1583'" @click="handleDeleteData(row.id)">删除</el-button>
								</template>
							</template>
							<template v-if="userRole === 'principal'">
								<template v-if="row.audit !== '1'">
									<el-button type="text" v-hasPermi="'cd86fec4b1654256bf123306af7c4b1a'" @click="handleAuditData(row.id)">审核</el-button>
								</template>
							</template>
							<template v-if="userRole === 'manager'">
								<el-button type="text" v-hasPermi="'d5f4538b53704c49bb6d28cee6a68603'" @click="handleManageEdit(row.id)">编辑</el-button>
								<el-button type="text" v-hasPermi="'4bf9b6b3eb9f47df9cd4e04417bf1583'" @click="handleReturnApply(row)">退回</el-button>
							</template>
						</template>
					</el-table-column>
				</el-table>
			</template>
			<el-empty v-else :image-size="120"></el-empty>
		</div>
		<template v-if="dataCount > 0">
			<sw-pagination :total="dataCount" :page.sync="queryData.page" :limit.sync="queryData.limit" @change="queryTableData"></sw-pagination>
		</template>
	</div>
</template>

<script>
import listMixins from '../listMixins1';
import { queryScheduleList } from '@/api/business/tbPiStat';
import { queryPageList, queryUserPageList, queryAuditPageList, batchDeleteData, experimentDetail, updateExperiment } from '@/api/business/tbExperiment';
export default {
	mixins: [listMixins],
	data() {
		return {
			tableConfig: {
				ref: 'table',
				size: 'medium',
				height: '100%',
				class: 'index_table_wrapper'
			}
		};
	},
	computed: {
		dataListRequest() {
			if (this.userRole === 'manager') {
				return queryPageList;
			} else if (this.userRole === 'principal') {
				return queryAuditPageList;
			} else if (this.userRole === 'member') {
				return queryUserPageList;
			}
		},
		topButton() {
			return ['60c75eefa71e4162bcb961ac142fa4c3', '4bf9b6b3eb9f47df9cd4e04417bf1583'];
		},
		topFrames() {
			return [...this.topButton, this.queryBtn];
		},
		tableButton() {
			let detail = '25bd663cfb6844758245a5d4e690198c';
			if (this.userRole === 'manager') {
				return [detail, 'd5f4538b53704c49bb6d28cee6a68603', '4bf9b6b3eb9f47df9cd4e04417bf1583'];
			} else if (this.userRole === 'principal') {
				return [detail, 'cd86fec4b1654256bf123306af7c4b1a'];
			} else if (this.userRole === 'member') {
				return [detail, 'd5f4538b53704c49bb6d28cee6a68603', '4bf9b6b3eb9f47df9cd4e04417bf1583'];
			}
		}
	},
	methods: {
		//请求参数
		formatQueryParams() {
			let params = { ...this.queryData };
			if (this.userRole === 'manager') {
				params['isSave'] = '1';
			}
			return params;
		},

		//获取课题列表数据
		async getTableData() {
			let params = this.formatQueryParams();
			let result = await this.dataListRequest(params).then((res) => res.data);
			this.loading = false;
			if (result.code === '0') {
				this.dataCount = parseInt(result.count);
				this.tableData = result.data || [];
			}
		},

		//删除数据请求
		async deleteDataRequest(id) {
			let params = !id ? this.checkedData.map((n) => n.id) : [id];
			let result = await batchDeleteData(params).then((res) => res.data);
			if (result.code === '0') {
				this.$showCustomMessage('success', `删除数据成功`);
				this.queryTableData();
			}
		},

		//课题状态格式化
		statusFormatter(row) {
			let statusAttrs = { size: 'medium' };
			let statusData = this.$getDataStatus(row);
			statusAttrs['type'] = statusData.type;
			return this.$createElement('elTag', { attrs: statusAttrs }, statusData.text);
		},

		async handleReturnApply(data) {
			if (!!(await this.isExistSchedule(data))) {
				this.$message.warning('该实验已被申请开始实验，无法退回');
			} else {
				let tipsText = data.audit !== '3' ? 'PI重新审核' : '用户重新提交';
				this.$confirm(`此操作将退回实验申请到${tipsText}, 是否继续?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
					beforeClose: async (action, instance, done) => {
						if (action === 'confirm') {
							instance.confirmButtonLoading = true;
							await this.returnApplyRequest(data.id);
							instance.confirmButtonLoading = false;
							done();
						} else {
							done();
						}
					}
				}).catch(() => {});
			}
		},

		//是否存在实验安排
		async isExistSchedule(data) {
			let params = { page: 1, limit: 1, filed10: data.id };
			let result = await queryScheduleList(params).then((res) => res.data);
			if (result.code === '0') {
				let datas = result.data || [];
				return Promise.resolve(datas.length > 0);
			} else {
				return Promise.resolve(false);
			}
		},

		//退回申请请求
		async returnApplyRequest(id) {
			let detailData = await experimentDetail(id).then((res) => res.data);
			if (detailData.code === '0') {
				let params = { ...this.$detailData(detailData.data) };
				if (params.audit === '3') {
					params['isSave'] = '2';
				} else {
					params['audit'] = '3';
				}
				let result = await updateExperiment(params).then((res) => res.data);
				if (result.code === '0') {
					this.$message.success('退回实验申请成功');
					this.queryTableData();
				}
			}
		},

		//排序
		handleSortChange(data) {
			let propData = data.prop.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
			if (data.order === 'ascending') {
				this.$set(this.queryData, 'sortStr', `${propData} asc`);
			} else if (data.order === 'descending') {
				this.$set(this.queryData, 'sortStr', `${propData} desc`);
			} else {
				this.$delete(this.queryData, 'sortStr');
			}
			this.$set(this.queryData, 'page', 1);
			this.queryTableData();
		}
	}
};
</script>

<style lang="scss" scoped></style>
